#pragma once
#include <iostream>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include"Log.hpp"
#include<cstring>
#include"InetAddr.hpp"
#include<sys/wait.h>
using namespace std;
const static uint16_t gport = 6666;
const static int gsock = -1;
const static int gblcklog = 8;
enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR
};

class TcpServer
{
public:
    TcpServer(uint16_t port=gport):_port(port),_listensockfd(gsock)
    {
    }
    class ThreadDate
    {
    public:
    ThreadDate(int sockfd,TcpServer* self,const InetAddr& addr):_sockfd(sockfd),_self(self),_addr(addr)
    {}
        int _sockfd;
        TcpServer *_self;
        InetAddr _addr;
    };
    void InitServer()
    {
        _listensockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if(_listensockfd<0)
        {
            LOG(FATAL, "socket create error\n");
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success\n");
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        int n = ::bind(_listensockfd, (sockaddr *)&local, sizeof(local));
        if(n<0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(INFO, "bind success\n");

        //tcp面向连接，要求不断获取连接，因此设为listen状态
        if(::listen(_listensockfd,gblcklog)<0)
        {
            LOG(FATAL, "listen error\n");
            exit(LISTEN_ERROR);
        }
        LOG(INFO, "listen success\n");

    }
    void Loop()
    {
        _isrunning = true;
        while(_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            int sockfd = ::accept(_listensockfd, (struct sockaddr *)&client, &len);
            if(sockfd<0)
            {
                LOG(WARNING, "accept error\n");
                continue;
            }
            InetAddr addr(client);
            LOG(INFO, "new connect %s\n",addr.Ip().c_str());
            // //多进行版本
            // pid_t id=fork();
            // if(id==0)
            // {
            //     ::close(_listensockfd);
            //     //让孙子变成孤儿，然后执行任务
            //     if(fork()>0)
            //         exit(0);
            //     Service(sockfd,addr);
            //     exit(0);
            // }
            // ::close(sockfd);
            // int n = waitpid(id, nullptr, 0);
            // if(n>0)
            // {
            //     LOG(INFO, "wait child success\n");
            // }
            
            //多线程版本，每个执行流去处理对应用户
            pthread_t tid;
            ThreadDate *td = new ThreadDate(sockfd, this,addr);
            pthread_create(&tid, nullptr, Excute, td);
        }
    }
    static void* Excute(void* args)
    {
        pthread_detach(pthread_self());
        ThreadDate *td = static_cast<ThreadDate *>(args);
        td->_self->Service(td->_sockfd,td->_addr);
        delete td;
        return nullptr;
    }
    void Service(int sockfd,InetAddr addr)
    {
        while(1)
        {
            char buf[512];
            ssize_t n = ::read(sockfd, buf, sizeof(buf) - 1);
            if(n>0)
            {
                buf[n] = 0;
                string msg = "[" + addr.Ip() + "]:" + buf;
                ::write(sockfd, msg.c_str(), msg.size());
            }
            else if(n==0)
            {
                LOG(INFO, "client %s quit\n", addr.Ip().c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read %s error\n", addr.Ip().c_str());
                break;
            }
        }
        ::close(sockfd);
    }
    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    int _listensockfd;
    bool _isrunning=false;

};